package com.czl.module_storehouse.adapter;

import android.annotation.SuppressLint;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.czl.base.data.bean.tengyun.SortBean;
import com.czl.base.data.bean.tengyun.SortNumType;
import com.czl.base.util.SpHelper;
import com.czl.module_base.utils.NumberUtils;
import com.czl.module_storehouse.R;
import com.czl.module_service.system.Constants;

import java.util.List;

/**
 * @author xubin
 */
public class AllocatePostInAdapter extends BaseNumAdapter<SortBean> implements View.OnFocusChangeListener, View.OnTouchListener {

    private int mTouchItemPosition = -1;
    private final boolean isInCompany;

    private final String locationName = SpHelper.INSTANCE.decodeString(Constants.SpKey.STOREHOUSE_LOCATION_NAME);

    public AllocatePostInAdapter(int layoutResId, @Nullable List<SortBean> data, boolean isInCompany) {
        super(layoutResId, data);
        this.isInCompany = isInCompany;
    }

    @Override
    protected void convert(@NonNull BaseViewHolder helper, SortBean item) {
        item.setCount(item.getAllocateInNum());
        item.setDefaultNumType(SortNumType.Type.NUM_TYPE_STOCK);
        super.convert(helper, item);
        helper.setText(R.id.tv_model, "型号：" + item.getSortModel())
                .setText(R.id.tv_date, getDate(item))
                .setText(R.id.tv_add_name, item.getSortName())
                .setText(R.id.et_num, item.getPrice())
                .setEnabled(R.id.et_num, !isInCompany(item, isInCompany))
                .setText(R.id.tv_apply_num, "调拨：" + item.lendNum())
                .setText(R.id.et_vendor, item.getManufacturer())
                .setVisible(R.id.tv_add_goods, isInCompany(item, isInCompany))
                .setText(R.id.tv_product_loc, getAllocateLocatText(item, isInCompany))
                .setText(R.id.tv_allocate_num, "数量：" + item.getLocationProductNum())
                .setText(R.id.tv_allocated_num, "已调：" + item.returnNum())
                .setVisible(R.id.tv_allocate_num, isScanCode(item, isInCompany))
                .setVisible(R.id.ll_sort_num, !isScanCode(item, isInCompany))
                .setEnabled(R.id.et_vendor, item.getExistCompanyBol(isInCompany))
                .setEnabled(R.id.et_num, false)
                .setEnabled(R.id.tv_date, item.getExistCompanyBol(isInCompany))
//                .setEnabled(R.id.tv_product_loc, item.getExistCompanyBol(isInCompany))
//                .setEnabled(R.id.iv_right, item.getExistCompanyBol(isInCompany))
                .setEnabled(R.id.tv_quantity, item.getExistCompanyBol(isInCompany))
                .setEnabled(R.id.text_remove, item.getExistCompanyBol(isInCompany))
                .setEnabled(R.id.text_add, item.getExistCompanyBol(isInCompany));
        helper.getView(R.id.tv_date).setOnClickListener(v -> {
            if (getOnItemChildClickListener() != null) {
                getOnItemChildClickListener().onItemChildClick(AllocatePostInAdapter.this, v, helper.getLayoutPosition() - getHeaderLayoutCount());
            }
        });
        helper.getView(R.id.tv_product_loc).setOnClickListener(v -> {
            if (getOnItemChildClickListener() != null) {
                getOnItemChildClickListener().onItemChildClick(AllocatePostInAdapter.this, v, helper.getLayoutPosition() - getHeaderLayoutCount());
            }
        });
        helper.getView(R.id.iv_right).setOnClickListener(v -> {
            if (getOnItemChildClickListener() != null) {
                getOnItemChildClickListener().onItemChildClick(AllocatePostInAdapter.this, v, helper.getLayoutPosition() - getHeaderLayoutCount());
            }
        });
        helper.getView(R.id.tv_add_goods).setOnClickListener(v -> {
            if (getOnItemChildClickListener() != null) {
                getOnItemChildClickListener().onItemChildClick(AllocatePostInAdapter.this, v, helper.getLayoutPosition() - getHeaderLayoutCount());
            }
        });
        EditText etVendor = helper.getView(R.id.et_vendor);
        EditText etNum = helper.getView(R.id.et_num);
        setEditText(etVendor, helper.getLayoutPosition());
        setEditText(etNum, helper.getLayoutPosition());

    }

    public String getDate(SortBean bean) {
        if (bean == null) {
            return "请选择生产日期";
        }
        String manufactureDate = bean.getManufactureDate();
        if (TextUtils.isEmpty(manufactureDate)) {
            return "请选择生产日期";
        } else {
            return manufactureDate;
        }
    }

    public String getAllocateLocatText(SortBean sortBean, boolean isInCompany) {
        //调拨
        if (sortBean.pasteCode() && sortBean.getExistCompanyBol(isInCompany)) {
            return sortBean.getLocatProductText(locationName);
        }
        return sortBean.getLocText(SpHelper.INSTANCE.decodeInt(Constants.SpKey.STOREHOUSE_LOCATION_ID), locationName);
    }

    public boolean isInCompany(SortBean sortBean, boolean isInCompany) {
        if (sortBean.getExistCompany() != null) {
            return !sortBean.getExistCompany();
        }
        if (sortBean.getInSortId() == null) {
            return false;
        }
        return !isInCompany && sortBean.getInSortId().equals(sortBean.getSortId());
    }

    public boolean isScanCode(SortBean sortBean, boolean isInCompany) {
        if (!isInCompany) {
            return true;
        }
        return sortBean.pasteCode();
    }

    @Override
    public int getMaxCount(SortBean item) {
        return item.getAllocatedInNum();
    }

    @Override
    public int getMinCount(SortBean item) {
        return item.getLocatTotalNum() == null ? 0 : item.getLocatTotalNum();
    }

    @Override
    protected void setAfterTextChanged(BaseViewHolder helper, SortBean item, int count) {
        if (item != null) {
            item.setDefaultLocatStock(count, SpHelper.INSTANCE.decodeInt(Constants.SpKey.STOREHOUSE_LOCATION_ID), locationName);
            helper.setText(R.id.tv_product_loc, item.getLocText(SpHelper.INSTANCE.decodeInt(Constants.SpKey.STOREHOUSE_LOCATION_ID), locationName));
        }
        if (mOnNumChangeListener != null) {
            mOnNumChangeListener.onChange(count);
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    private void setEditText(EditText editText, int position) {
        editText.setOnTouchListener(this);
        editText.setOnFocusChangeListener(this);
        editText.setTag(position - getHeaderLayoutCount());
        //保证每个时刻只有一个EditText能获取到焦点
        if (mTouchItemPosition != -1 && position == mTouchItemPosition) {
            editText.requestFocus();
        } else {
            editText.clearFocus();
        }
        editText.setSelection(editText.length());
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        EditText editText = (EditText) v;
        int id = editText.getId();
        if (id == R.id.et_vendor) {
            if (hasFocus) {
                editText.addTextChangedListener(mVendorTextWatcher);
            } else {
                editText.removeTextChangedListener(mVendorTextWatcher);
            }
        } else if (id == R.id.et_num) {
            if (hasFocus) {
                editText.addTextChangedListener(mPriceTextWatcher);
            } else {
                editText.removeTextChangedListener(mPriceTextWatcher);
            }
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public boolean onTouch(View view, MotionEvent event) {
        //onTouch 获取焦点
        if (event.getAction() == MotionEvent.ACTION_UP) {
            EditText editText = (EditText) view;
            mTouchItemPosition = (int) editText.getTag();
        }
        return false;
    }

    private final TextWatcher mVendorTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            String text = editable.toString();
            if (mTouchItemPosition < getData().size()) {
                SortBean sortBean = getData().get(mTouchItemPosition);
                sortBean.setManufacturer(editable.toString());
            }
        }
    };

    private final TextWatcher mPriceTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            String text = editable.toString();
            if (NumberUtils.isDouble(text)) {
                if (mTouchItemPosition < getData().size()) {
                    SortBean sortBean = getData().get(mTouchItemPosition);
                    sortBean.setPrice(text);
                }
            }
        }
    };

}

